<?php
namespace app\admin\controller;
use think\Controller;
use think\facade\Session;
use think\Request;
use app\admin\model\Login as LM;
use app\admin\validate\AdminValidate;


class Login extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    //管理员登录
    public function login(Request $request){
        
        if($request->isAjax()){
            $param = $request->param();
            $validate = new AdminValidate();
            
            if(!$validate->scene($validate::SCENE_LOGIN)->check($param)){
                die(outputError($validate->getError()));
            }
            
            $model = new LM();
            if(!$model->_login($param)){
                 die(outputError($model->getError()));
            }
            die(outputSuccess([], '登录成功'));
        }
    }
    
    
    public function verify($len=4,$width=100,$height=40,$font_size=20,$font_type="arial.ttf"){
        $verify = get_rand_str($len);
        //session_start();
        //$_SESSION['verify'] = $verify;
        Session::set('verify', $verify);
        
        //session('verify', $verify);
        $len = strlen($verify);
        $img = imagecreatetruecolor($width, $height); 
        // 定义要用到的颜色
        $back_color = imagecolorallocate($img, 235, 236, 237);
        $boder_color = imagecolorallocate($img, 118, 151, 199);

        // 画背景
        imagefilledrectangle($img, 0, 0, $width, $height, $back_color); 
        // 画边框
        imagerectangle($img, 0, 0, $width-1, $height-1, $boder_color);
        // 画干扰线
        for($i = 0;$i < 5;$i++) {
            $line_color = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
            imageline($img, 0, mt_rand(0,$height), $width, mt_rand(0,$height), $line_color);
        } 
        // 画干扰点
        for($i = 0;$i < 100;$i++) {
            $point_color = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
            imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), $point_color);
        }
        
        if(!file_exists($font_type)){
            $font_type = APP_PATH.$font_type;
        }
        //写数据
        for($i=0; $i<$len; $i++){
            $code = substr($verify,$i,1);
            $text_color = imagecolorallocate($img, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120)); 
            imagefttext($img,$font_size,mt_rand(5,50),($width-$font_size*$len)/2+($i*$font_size),($font_size+$height)/2,$text_color,$font_type,$code);
        }
        //imagefttext($img,$font_size,0,($width-$font_size*$len)/2,($font_size+$height)/2,$text_color,$font_type,$verify);
        header("Content-type: image/png");
        imagepng($img);
        imagedestroy($img);
    }
}
